[[...path]].page.tsx 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655
  1. import React, { ReactNode, useEffect } from 'react';
  2. import EventEmitter from 'events';
  3. import { isIPageInfoForEntity } from '@growi/core';
  4. import type {
  5. IDataWithMeta, IPageInfoForEntity, IPagePopulatedToShowRevision, IUserHasId,
  6. } from '@growi/core';
  7. import {
  8. isClient, pagePathUtils, pathUtils,
  9. } from '@growi/core/dist/utils';
  10. import ExtensibleCustomError from 'extensible-custom-error';
  11. import type {
  12. GetServerSideProps, GetServerSidePropsContext,
  13. } from 'next';
  14. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  15. import dynamic from 'next/dynamic';
  16. import Head from 'next/head';
  17. import { useRouter } from 'next/router';
  18. import superjson from 'superjson';
  19. import { useLayoutFluidClassNameByPage, useEditorModeClassName } from '~/client/services/layout';
  20. import { PageView } from '~/components/Page/PageView';
  21. import { DrawioViewerScript } from '~/components/Script/DrawioViewerScript'; import type { CrowiRequest } from '~/interfaces/crowi-request';
  22. import type { EditorConfig } from '~/interfaces/editor-settings';
  23. import type { IPageGrantData } from '~/interfaces/page';
  24. import type { RendererConfig } from '~/interfaces/services/renderer';
  25. import type { PageModel, PageDocument } from '~/server/models/page';
  26. import type { PageRedirectModel } from '~/server/models/page-redirect';
  27. import {
  28. useCurrentUser,
  29. useIsForbidden, useIsSharedUser,
  30. useIsEnabledStaleNotification, useIsIdenticalPath,
  31. useIsSearchServiceConfigured, useIsSearchServiceReachable, useDisableLinkSharing,
  32. useDefaultIndentSize, useIsIndentSizeForced,
  33. useIsAclEnabled, useIsSearchPage, useIsEnabledAttachTitleHeader,
  34. useCsrfToken, useIsSearchScopeChildrenAsDefault, useIsEnabledMarp, useCurrentPathname,
  35. useIsSlackConfigured, useRendererConfig, useGrowiCloudUri,
  36. useEditorConfig, useIsAllReplyShown, useIsUploadableFile, useIsUploadableImage, useIsContainerFluid, useIsNotCreatable,
  37. } from '~/stores/context';
  38. import { useEditingMarkdown } from '~/stores/editor';
  39. import {
  40. useSWRxCurrentPage, useSWRMUTxCurrentPage, useSWRxIsGrantNormalized, useCurrentPageId,
  41. useIsNotFound, useIsLatestRevision, useTemplateTagData, useTemplateBodyData,
  42. } from '~/stores/page';
  43. import { useRedirectFrom } from '~/stores/page-redirect';
  44. import { useRemoteRevisionId } from '~/stores/remote-latest-page';
  45. import { useSelectedGrant } from '~/stores/ui';
  46. import { useSetupGlobalSocket, useSetupGlobalSocketForPage } from '~/stores/websocket';
  47. import loggerFactory from '~/utils/logger';
  48. import { BasicLayout } from '../components/Layout/BasicLayout';
  49. import GrowiContextualSubNavigationSubstance from '../components/Navbar/GrowiContextualSubNavigation';
  50. import { DisplaySwitcher } from '../components/Page/DisplaySwitcher';
  51. import type { NextPageWithLayout } from './_app.page';
  52. import type { CommonProps } from './utils/commons';
  53. import {
  54. getNextI18NextConfig, getServerSideCommonProps, generateCustomTitleForPage, useInitSidebarConfig, skipSSR,
  55. } from './utils/commons';
  56. declare global {
  57. // eslint-disable-next-line vars-on-top, no-var
  58. var globalEmitter: EventEmitter;
  59. }
  60. const GrowiPluginsActivator = dynamic(() => import('~/features/growi-plugin/client/components').then(mod => mod.GrowiPluginsActivator), { ssr: false });
  61. const DescendantsPageListModal = dynamic(() => import('../components/DescendantsPageListModal').then(mod => mod.DescendantsPageListModal), { ssr: false });
  62. const UnsavedAlertDialog = dynamic(() => import('../components/UnsavedAlertDialog'), { ssr: false });
  63. const DrawioModal = dynamic(() => import('../components/PageEditor/DrawioModal').then(mod => mod.DrawioModal), { ssr: false });
  64. const HandsontableModal = dynamic(() => import('../components/PageEditor/HandsontableModal').then(mod => mod.HandsontableModal), { ssr: false });
  65. const TemplateModal = dynamic(() => import('../components/TemplateModal').then(mod => mod.TemplateModal), { ssr: false });
  66. const LinkEditModal = dynamic(() => import('../components/PageEditor/LinkEditModal').then(mod => mod.LinkEditModal), { ssr: false });
  67. const PageStatusAlert = dynamic(() => import('../components/PageStatusAlert').then(mod => mod.PageStatusAlert), { ssr: false });
  68. const QuestionnaireModalManager = dynamic(() => import('~/features/questionnaire/client/components/QuestionnaireModalManager'), { ssr: false });
  69. const logger = loggerFactory('growi:pages:all');
  70. const {
  71. isPermalink: _isPermalink, isCreatablePage,
  72. } = pagePathUtils;
  73. const { removeHeadingSlash } = pathUtils;
  74. type IPageToShowRevisionWithMeta = IDataWithMeta<IPagePopulatedToShowRevision & PageDocument, IPageInfoForEntity>;
  75. type IPageToShowRevisionWithMetaSerialized = IDataWithMeta<string, string>;
  76. superjson.registerCustom<IPageToShowRevisionWithMeta, IPageToShowRevisionWithMetaSerialized>(
  77. {
  78. isApplicable: (v): v is IPageToShowRevisionWithMeta => {
  79. return v?.data != null
  80. && v?.data.toObject != null
  81. && v?.meta != null
  82. && isIPageInfoForEntity(v.meta);
  83. },
  84. serialize: (v) => {
  85. return {
  86. data: superjson.stringify(v.data.toObject()),
  87. meta: superjson.stringify(v.meta),
  88. };
  89. },
  90. deserialize: (v) => {
  91. return {
  92. data: superjson.parse(v.data),
  93. meta: v.meta != null ? superjson.parse(v.meta) : undefined,
  94. };
  95. },
  96. },
  97. 'IPageToShowRevisionWithMetaTransformer',
  98. );
  99. // GrowiContextualSubNavigation for NOT shared page
  100. type GrowiContextualSubNavigationProps = {
  101. isLinkSharingDisabled: boolean,
  102. }
  103. const GrowiContextualSubNavigation = (props: GrowiContextualSubNavigationProps): JSX.Element => {
  104. const { isLinkSharingDisabled } = props;
  105. const { data: currentPage } = useSWRxCurrentPage();
  106. return (
  107. <div data-testid="grw-contextual-sub-nav">
  108. <GrowiContextualSubNavigationSubstance currentPage={currentPage} isLinkSharingDisabled={isLinkSharingDisabled} />
  109. </div>
  110. );
  111. };
  112. type Props = CommonProps & {
  113. pageWithMeta: IPageToShowRevisionWithMeta | null,
  114. // pageUser?: any,
  115. redirectFrom?: string;
  116. // shareLinkId?: string;
  117. isLatestRevision?: boolean,
  118. isIdenticalPathPage?: boolean,
  119. isForbidden: boolean,
  120. isNotFound: boolean,
  121. isNotCreatable: boolean,
  122. // isAbleToDeleteCompletely: boolean,
  123. templateTagData?: string[],
  124. templateBodyData?: string,
  125. isSearchServiceConfigured: boolean,
  126. isSearchServiceReachable: boolean,
  127. isSearchScopeChildrenAsDefault: boolean,
  128. isEnabledMarp: boolean,
  129. isSlackConfigured: boolean,
  130. // isMailerSetup: boolean,
  131. isAclEnabled: boolean,
  132. // hasSlackConfig: boolean,
  133. drawioUri: string | null,
  134. noCdn: string,
  135. // highlightJsStyle: string,
  136. isAllReplyShown: boolean,
  137. isContainerFluid: boolean,
  138. editorConfig: EditorConfig,
  139. isEnabledStaleNotification: boolean,
  140. isEnabledAttachTitleHeader: boolean,
  141. // isEnabledLinebreaks: boolean,
  142. // isEnabledLinebreaksInComments: boolean,
  143. adminPreferredIndentSize: number,
  144. isIndentSizeForced: boolean,
  145. disableLinkSharing: boolean,
  146. skipSSR: boolean,
  147. ssrMaxRevisionBodyLength: number,
  148. grantData?: IPageGrantData,
  149. rendererConfig: RendererConfig,
  150. };
  151. const Page: NextPageWithLayout<Props> = (props: Props) => {
  152. // register global EventEmitter
  153. if (isClient() && window.globalEmitter == null) {
  154. window.globalEmitter = new EventEmitter();
  155. }
  156. const router = useRouter();
  157. useCurrentUser(props.currentUser ?? null);
  158. // commons
  159. useEditorConfig(props.editorConfig);
  160. useCsrfToken(props.csrfToken);
  161. useGrowiCloudUri(props.growiCloudUri);
  162. // page
  163. useIsContainerFluid(props.isContainerFluid);
  164. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  165. useIsForbidden(props.isForbidden);
  166. useIsNotCreatable(props.isNotCreatable);
  167. useRedirectFrom(props.redirectFrom ?? null);
  168. useIsSharedUser(false); // this page cann't be routed for '/share'
  169. useIsIdenticalPath(props.isIdenticalPathPage ?? false);
  170. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  171. useIsSearchPage(false);
  172. useIsEnabledAttachTitleHeader(props.isEnabledAttachTitleHeader);
  173. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  174. useIsSearchServiceReachable(props.isSearchServiceReachable);
  175. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  176. useIsSlackConfigured(props.isSlackConfigured);
  177. // useIsMailerSetup(props.isMailerSetup);
  178. useIsAclEnabled(props.isAclEnabled);
  179. // useHasSlackConfig(props.hasSlackConfig);
  180. // useNoCdn(props.noCdn);
  181. useDefaultIndentSize(props.adminPreferredIndentSize);
  182. useIsIndentSizeForced(props.isIndentSizeForced);
  183. useDisableLinkSharing(props.disableLinkSharing);
  184. useRendererConfig(props.rendererConfig);
  185. useIsEnabledMarp(props.rendererConfig.isEnabledMarp);
  186. // useRendererSettings(props.rendererSettingsStr != null ? JSON.parse(props.rendererSettingsStr) : undefined);
  187. // useGrowiRendererConfig(props.growiRendererConfigStr != null ? JSON.parse(props.growiRendererConfigStr) : undefined);
  188. useIsAllReplyShown(props.isAllReplyShown);
  189. useIsUploadableFile(props.editorConfig.upload.isUploadableFile);
  190. useIsUploadableImage(props.editorConfig.upload.isUploadableImage);
  191. const { pageWithMeta } = props;
  192. const pageId = pageWithMeta?.data._id;
  193. const pagePath = pageWithMeta?.data.path ?? props.currentPathname;
  194. const revisionBody = pageWithMeta?.data.revision?.body;
  195. useCurrentPathname(props.currentPathname);
  196. useSWRxCurrentPage(pageWithMeta?.data ?? null); // store initial data
  197. const { trigger: mutateCurrentPage } = useSWRMUTxCurrentPage();
  198. const { mutate: mutateEditingMarkdown } = useEditingMarkdown();
  199. const { data: currentPageId, mutate: mutateCurrentPageId } = useCurrentPageId();
  200. const { mutate: mutateIsNotFound } = useIsNotFound();
  201. const { mutate: mutateIsLatestRevision } = useIsLatestRevision();
  202. const { data: grantData } = useSWRxIsGrantNormalized(pageId);
  203. const { mutate: mutateSelectedGrant } = useSelectedGrant();
  204. const { mutate: mutateRemoteRevisionId } = useRemoteRevisionId();
  205. const { mutate: mutateTemplateTagData } = useTemplateTagData();
  206. const { mutate: mutateTemplateBodyData } = useTemplateBodyData();
  207. useSetupGlobalSocket();
  208. useSetupGlobalSocketForPage(pageId);
  209. const growiLayoutFluidClass = useLayoutFluidClassNameByPage(pageWithMeta?.data);
  210. // Store initial data (When revisionBody is not SSR)
  211. useEffect(() => {
  212. if (!props.skipSSR) {
  213. return;
  214. }
  215. if (currentPageId != null && !props.isNotFound) {
  216. const mutatePageData = async() => {
  217. const pageData = await mutateCurrentPage();
  218. mutateEditingMarkdown(pageData?.revision.body);
  219. };
  220. // If skipSSR is true, use the API to retrieve page data.
  221. // Because pageWIthMeta does not contain revision.body
  222. mutatePageData();
  223. }
  224. }, [currentPageId, mutateCurrentPage, mutateEditingMarkdown, props.isNotFound, props.skipSSR]);
  225. // sync grant data
  226. useEffect(() => {
  227. const grantDataToApply = props.grantData ? props.grantData : grantData?.grantData.currentPageGrant;
  228. mutateSelectedGrant(grantDataToApply);
  229. }, [grantData?.grantData.currentPageGrant, mutateSelectedGrant, props.grantData]);
  230. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  231. useEffect(() => {
  232. const decodedURI = decodeURI(window.location.pathname);
  233. if (isClient() && decodedURI !== props.currentPathname) {
  234. const { search, hash } = window.location;
  235. router.replace(`${props.currentPathname}${search}${hash}`, undefined, { shallow: true });
  236. }
  237. }, [props.currentPathname, router]);
  238. // initialize mutateEditingMarkdown only once per page
  239. // need to include useCurrentPathname not useCurrentPagePath
  240. useEffect(() => {
  241. if (props.currentPathname != null) {
  242. mutateEditingMarkdown(revisionBody);
  243. }
  244. }, [mutateEditingMarkdown, revisionBody, props.currentPathname]);
  245. useEffect(() => {
  246. mutateRemoteRevisionId(pageWithMeta?.data.revision?._id);
  247. }, [mutateRemoteRevisionId, pageWithMeta?.data.revision?._id]);
  248. useEffect(() => {
  249. mutateCurrentPageId(pageId ?? null);
  250. }, [mutateCurrentPageId, pageId]);
  251. useEffect(() => {
  252. mutateIsNotFound(props.isNotFound);
  253. }, [mutateIsNotFound, props.isNotFound]);
  254. useEffect(() => {
  255. mutateIsLatestRevision(props.isLatestRevision);
  256. }, [mutateIsLatestRevision, props.isLatestRevision]);
  257. useEffect(() => {
  258. mutateTemplateTagData(props.templateTagData);
  259. }, [props.templateTagData, mutateTemplateTagData]);
  260. useEffect(() => {
  261. mutateTemplateBodyData(props.templateBodyData);
  262. }, [props.templateBodyData, mutateTemplateBodyData]);
  263. const title = generateCustomTitleForPage(props, pagePath);
  264. return (
  265. <>
  266. <Head>
  267. <title>{title}</title>
  268. </Head>
  269. <div className={`dynamic-layout-root ${growiLayoutFluidClass} justify-content-between`}>
  270. <header className="py-0 position-relative">
  271. <div id="grw-subnav-container">
  272. <GrowiContextualSubNavigation isLinkSharingDisabled={props.disableLinkSharing} />
  273. </div>
  274. </header>
  275. <DisplaySwitcher
  276. pageView={(
  277. <PageView
  278. pagePath={pagePath}
  279. initialPage={pageWithMeta?.data}
  280. rendererConfig={props.rendererConfig}
  281. />
  282. )}
  283. />
  284. <PageStatusAlert />
  285. </div>
  286. </>
  287. );
  288. };
  289. type LayoutProps = Props & {
  290. children?: ReactNode
  291. }
  292. const Layout = ({ children, ...props }: LayoutProps): JSX.Element => {
  293. const className = useEditorModeClassName();
  294. // init sidebar config with UserUISettings and sidebarConfig
  295. useInitSidebarConfig(props.sidebarConfig, props.userUISettings);
  296. return (
  297. <BasicLayout className={className}>
  298. {children}
  299. </BasicLayout>
  300. );
  301. };
  302. Page.getLayout = function getLayout(page: React.ReactElement<Props>) {
  303. return (
  304. <>
  305. <GrowiPluginsActivator />
  306. <DrawioViewerScript />
  307. <Layout {...page.props}>
  308. {page}
  309. </Layout>
  310. <UnsavedAlertDialog />
  311. <DescendantsPageListModal />
  312. <DrawioModal />
  313. <HandsontableModal />
  314. <QuestionnaireModalManager />
  315. <TemplateModal />
  316. <LinkEditModal />
  317. </>
  318. );
  319. };
  320. function getPageIdFromPathname(currentPathname: string): string | null {
  321. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  322. }
  323. class MultiplePagesHitsError extends ExtensibleCustomError {
  324. pagePath: string;
  325. constructor(pagePath: string) {
  326. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  327. this.pagePath = pagePath;
  328. }
  329. }
  330. // apply parent page grant fot creating page
  331. async function applyGrantToPage(props: Props, ancestor: any) {
  332. await ancestor.populate('grantedGroup');
  333. const grant = {
  334. grant: ancestor.grant,
  335. };
  336. const grantedGroup = ancestor.grantedGroup ? {
  337. grantedGroup: {
  338. id: ancestor.grantedGroup.id,
  339. name: ancestor.grantedGroup.name,
  340. },
  341. } : {};
  342. props.grantData = Object.assign(grant, grantedGroup);
  343. }
  344. async function injectPageData(context: GetServerSidePropsContext, props: Props): Promise<void> {
  345. const { model: mongooseModel } = await import('mongoose');
  346. const req: CrowiRequest = context.req as CrowiRequest;
  347. const { crowi } = req;
  348. const { revisionId } = req.query;
  349. const Page = crowi.model('Page') as PageModel;
  350. const PageRedirect = mongooseModel('PageRedirect') as PageRedirectModel;
  351. const { pageService, configManager } = crowi;
  352. let currentPathname = props.currentPathname;
  353. const pageId = getPageIdFromPathname(currentPathname);
  354. const isPermalink = _isPermalink(currentPathname);
  355. const { user } = req;
  356. if (!isPermalink) {
  357. // check redirects
  358. const chains = await PageRedirect.retrievePageRedirectEndpoints(currentPathname);
  359. if (chains != null) {
  360. // overwrite currentPathname
  361. currentPathname = chains.end.toPath;
  362. props.currentPathname = currentPathname;
  363. // set redirectFrom
  364. props.redirectFrom = chains.start.fromPath;
  365. }
  366. // check whether the specified page path hits to multiple pages
  367. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  368. if (count > 1) {
  369. throw new MultiplePagesHitsError(currentPathname);
  370. }
  371. }
  372. const pageWithMeta: IPageToShowRevisionWithMeta | null = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  373. const page = pageWithMeta?.data as unknown as PageDocument;
  374. // add user to seen users
  375. if (page != null && user != null) {
  376. await page.seen(user);
  377. }
  378. // populate & check if the revision is latest
  379. if (page != null) {
  380. page.initLatestRevisionField(revisionId);
  381. props.isLatestRevision = page.isLatestRevision();
  382. const ssrMaxRevisionBodyLength = configManager.getConfig('crowi', 'app:ssrMaxRevisionBodyLength');
  383. props.skipSSR = await skipSSR(page, ssrMaxRevisionBodyLength);
  384. await page.populateDataToShowRevision(props.skipSSR); // shouldExcludeBody = skipSSR
  385. }
  386. if (page == null && user != null) {
  387. const templateData = await Page.findTemplate(props.currentPathname);
  388. if (templateData != null) {
  389. props.templateTagData = templateData.templateTags as string[];
  390. props.templateBodyData = templateData.templateBody as string;
  391. }
  392. // apply pagrent page grant
  393. const ancestor = await Page.findAncestorByPathAndViewer(currentPathname, user);
  394. if (ancestor != null) {
  395. await applyGrantToPage(props, ancestor);
  396. }
  397. }
  398. props.pageWithMeta = pageWithMeta;
  399. }
  400. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  401. const req: CrowiRequest = context.req as CrowiRequest;
  402. const { crowi } = req;
  403. const Page = crowi.model('Page') as PageModel;
  404. const { currentPathname } = props;
  405. const pageId = getPageIdFromPathname(currentPathname);
  406. const isPermalink = _isPermalink(currentPathname);
  407. const page = props.pageWithMeta?.data;
  408. if (props.isIdenticalPathPage) {
  409. props.isNotCreatable = true;
  410. }
  411. else if (page == null) {
  412. props.isNotFound = true;
  413. props.isNotCreatable = !isCreatablePage(currentPathname);
  414. // check the page is forbidden or just does not exist.
  415. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  416. props.isForbidden = count > 0;
  417. }
  418. else {
  419. props.isNotFound = page.isEmpty;
  420. props.isNotCreatable = false;
  421. props.isForbidden = false;
  422. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  423. if (isPermalink && page.isEmpty) {
  424. props.currentPathname = page.path;
  425. }
  426. // /path/to/page ==> /62a88db47fed8b2d94f30000
  427. if (!isPermalink && !page.isEmpty) {
  428. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  429. if (!isToppage) {
  430. props.currentPathname = `/${page._id}`;
  431. }
  432. }
  433. }
  434. }
  435. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  436. // const req: CrowiRequest = context.req as CrowiRequest;
  437. // const { crowi } = req;
  438. // const UserModel = crowi.model('User');
  439. // if (isUserPage(props.currentPagePath)) {
  440. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  441. // if (user != null) {
  442. // props.pageUser = JSON.stringify(user.toObject());
  443. // }
  444. // }
  445. // }
  446. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  447. const req: CrowiRequest = context.req as CrowiRequest;
  448. const { crowi } = req;
  449. const {
  450. searchService, configManager, aclService,
  451. } = crowi;
  452. props.isSearchServiceConfigured = searchService.isConfigured;
  453. props.isSearchServiceReachable = searchService.isReachable;
  454. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  455. props.isSlackConfigured = crowi.slackIntegrationService.isSlackConfigured;
  456. // props.isMailerSetup = mailService.isMailerSetup;
  457. props.isAclEnabled = aclService.isAclEnabled();
  458. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  459. props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  460. props.noCdn = configManager.getConfig('crowi', 'app:noCdn');
  461. // props.highlightJsStyle = configManager.getConfig('crowi', 'customize:highlightJsStyle');
  462. props.isAllReplyShown = configManager.getConfig('crowi', 'customize:isAllReplyShown');
  463. props.isContainerFluid = configManager.getConfig('crowi', 'customize:isContainerFluid');
  464. props.isEnabledStaleNotification = configManager.getConfig('crowi', 'customize:isEnabledStaleNotification');
  465. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  466. props.editorConfig = {
  467. upload: {
  468. isUploadableFile: crowi.fileUploadService.getFileUploadEnabled(),
  469. isUploadableImage: crowi.fileUploadService.getIsUploadable(),
  470. },
  471. };
  472. props.adminPreferredIndentSize = configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize');
  473. props.isIndentSizeForced = configManager.getConfig('markdown', 'markdown:isIndentSizeForced');
  474. props.isEnabledAttachTitleHeader = configManager.getConfig('crowi', 'customize:isEnabledAttachTitleHeader');
  475. props.rendererConfig = {
  476. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  477. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  478. isEnabledMarp: configManager.getConfig('crowi', 'customize:isEnabledMarp'),
  479. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  480. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  481. drawioUri: configManager.getConfig('crowi', 'app:drawioUri'),
  482. plantumlUri: configManager.getConfig('crowi', 'app:plantumlUri'),
  483. // XSS Options
  484. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:rehypeSanitize:isEnabledPrevention'),
  485. xssOption: configManager.getConfig('markdown', 'markdown:rehypeSanitize:option'),
  486. attrWhitelist: JSON.parse(crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:attributes')),
  487. tagWhitelist: crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:tagNames'),
  488. highlightJsStyleBorder: crowi.configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  489. };
  490. props.ssrMaxRevisionBodyLength = configManager.getConfig('crowi', 'app:ssrMaxRevisionBodyLength');
  491. }
  492. /**
  493. * for Server Side Translations
  494. * @param context
  495. * @param props
  496. * @param namespacesRequired
  497. */
  498. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  499. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  500. props._nextI18Next = nextI18NextConfig._nextI18Next;
  501. }
  502. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  503. const req = context.req as CrowiRequest<IUserHasId & any>;
  504. const { user } = req;
  505. const result = await getServerSideCommonProps(context);
  506. // check for presence
  507. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  508. if (!('props' in result)) {
  509. throw new Error('invalid getSSP result');
  510. }
  511. const props: Props = result.props as Props;
  512. if (props.redirectDestination != null) {
  513. return {
  514. redirect: {
  515. permanent: false,
  516. destination: props.redirectDestination,
  517. },
  518. };
  519. }
  520. if (user != null) {
  521. props.currentUser = user.toObject();
  522. }
  523. try {
  524. await injectPageData(context, props);
  525. }
  526. catch (err) {
  527. if (err instanceof MultiplePagesHitsError) {
  528. props.isIdenticalPathPage = true;
  529. }
  530. else {
  531. throw err;
  532. }
  533. }
  534. await injectRoutingInformation(context, props);
  535. injectServerConfigurations(context, props);
  536. await injectNextI18NextConfigurations(context, props, ['translation']);
  537. return {
  538. props,
  539. };
  540. };
  541. export default Page;